package com.common.secuity.filter;

import com.alibaba.fastjson2.JSON;
import com.common.entity.login.LoginUser;
import com.common.service.TokenService;
import com.common.utils.R;
import com.common.utils.auth.SecurityUtils;
import com.common.utils.auth.StringUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * token过滤器 验证token有效性
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final TokenService tokenService;


    public JwtAuthenticationTokenFilter(TokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        System.out.println(request.getRequestURI());
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (!request.getRequestURI().equals("/auth/login") && !request.getRequestURI().equals("/webHook/notify")) {
            String token = request.getHeader("Authorization");
            if(token == null){
                sendJsonError(response, 401, "未提供认证令牌");
                return;
            }
            if(loginUser == null){
                sendJsonError(response, 401, "令牌无效");
                return;
            }
            if (StringUtils.isNull(SecurityUtils.getAuthentication())) {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        chain.doFilter(request, response);
    }


    private void sendJsonError(HttpServletResponse response, int code, String message) throws IOException {
        response.setStatus(code);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(R.success(code,message)));
    }

}
